"""
server_info.py - A /info route that displays request details.
Designed to work even before the session module is added.
Later it will automatically show session and login status.
"""

from datetime import datetime

# Try to import the session module – it may not exist yet.
# This lets the /info page work during all development stages.
try:
    import session as session_mod  # type: ignore[import]
    HAS_SESSION = True
except ImportError:
    HAS_SESSION = False


def handle(handler):
    # Gather information that every HTTP request provides
    client_ip = handler.client_address[0]
    client_port = handler.client_address[1]
    request_line = f"{handler.command} {handler.path} {handler.request_version}"
    headers = handler.headers
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # Check if session data was attached by the main server
    has_session_data = (
        HAS_SESSION and
        hasattr(handler, 'session') and
        handler.session is not None
    )

    # Build the HTML page piece by piece
    body_parts = [
        '<!DOCTYPE html>',
        '<html>',
        '<head><title>Server Info</title></head>',
        '<body>',
        '<h1>Server Info</h1>',
        f'<p>Current server time: {current_time}</p>',
        f'<p>Client IP: {client_ip}:{client_port}</p>',
        f'<p>Request: <code>{request_line}</code></p>',
        '<h2>Session</h2>',
    ]

    if has_session_data:
        # Session is active – show details and increment a visit counter
        handler.session['visits'] = handler.session.get('visits', 0) + 1
        body_parts.extend([
            f'<p>Status: <strong>Active</strong></p>',
            f'<p>Session ID: {handler._sid}</p>',
            f'<p>New session? {"Yes" if handler._new_sid else "No"}</p>',
            f'<p>Visit count (this session): {handler.session["visits"]}</p>'
        ])
        if 'user' in handler.session:
            body_parts.append(f'<p>Logged in as: <strong>{handler.session["user"]}</strong></p>')
    else:
        # No session module loaded yet – show a helpful message
        body_parts.append('<p>Status: <strong>Sessions not active</strong></p>')
        if not HAS_SESSION:
            body_parts.append('<p>(session.py module not found)</p>')
        else:
            body_parts.append('<p>(ENABLE_SESSIONS may be False)</p>')

    # Show all HTTP headers the client sent
    body_parts.append('<h2>Request Headers</h2><ul>')
    for name, value in headers.items():
        body_parts.append(f'<li><strong>{name}:</strong> {value}</li>')
    body_parts.append('</ul>')
    body_parts.append('<p><a href="/">Go to home page</a></p>')
    body_parts.append('</body></html>')

    body = '\n'.join(body_parts)
    content = body.encode('utf-8')

    # Send the HTTP response
    handler.send_response(200)
    handler.send_header('Content-Type', 'text/html; charset=utf-8')
    handler.send_header('Content-Length', len(content))

    # If sessions are active and this is a new session, set the cookie
    if HAS_SESSION and getattr(handler, '_new_sid', False):
        session_mod.set_session_cookie(handler)

    handler.end_headers()
    handler.wfile.write(content)